import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

export const fetchPosts = createAsyncThunk('posts/fetchPosts', (res) => {
  console.log('res', res);

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('data');
    }, 1000);
  });
});

const todosSlice = createSlice({
  name: 'todos',
  initialState: {
    status: '',
    value: '',
  },
  reducers: {
    todoAdded(state, action) {
      state.value = action.payload.id;
    },
    todoToggled(state) {
      if (state.value) {
        state.value = '';
      }
    },
  },
  extraReducers(builder) {
    builder
      // .addCase(fetchPosts.pending, (state) => {
      //   state.status = 'loading';
      // })
      .addCase(fetchPosts.fulfilled, (state, action) => {
        state.status = 'succeeded';
        console.log('action', action);
        state.value = action.payload;
      });
    // .addCase(fetchPosts.rejected, (state, action) => {
    //   state.status = 'failed';
    //   console.log('action2', action);
    // });
  },
});

// console.log('todosSlice', todosSlice);
export const { todoAdded, todoToggled } = todosSlice.actions;
export default todosSlice.reducer;
